package com.chenyanqing.model.two.dao.impl;

import com.chenyanqing.model.two.dao.UserDao;
import com.chenyanqing.model.two.model.User;
import com.chenyanqing.model.two.utils.JDBCConnectionUtils;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;


/**
 * 传统的数据库查询实现，不走mybatis的mapper代理
 */
public class UserDaoImpl implements UserDao {


    @Override
    public int incrMoney(int id,int incrMoney) throws SQLException {
        Connection connection = JDBCConnectionUtils.getJDBCConnectionUtils().getCurrentThreadConnection();
        Statement statement = connection.createStatement();

        String sql = String.format("update user set money=money+%d where id=%d",incrMoney,id);
        int i = statement.executeUpdate(sql);
        return i;
    }

    @Override
    public User selectById(int id) throws SQLException, IntrospectionException, InvocationTargetException, IllegalAccessException {
        Connection connection = JDBCConnectionUtils.getJDBCConnectionUtils().getCurrentThreadConnection();
        Statement statement = connection.createStatement();

        String sql = String.format("select * from user where id=%d", id);

        ResultSet resultSet = statement.executeQuery(sql);

        User user = null;
        while (resultSet.next()) {
            user = new User();
            //元数据
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i <= metaData.getColumnCount(); i++) {

                // 字段名
                String columnName = metaData.getColumnName(i);
                // 字段的值
                Object value = resultSet.getObject(columnName);

                //使用反射或者内省，根据数据库表和实体的对应关系，完成封装
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, User.class);
                Method writeMethod = propertyDescriptor.getWriteMethod();
                writeMethod.invoke(user, value);

            }

            return user;
        }
        return null;
    }
}
